from django.shortcuts import render, redirect, HttpResponse
from django.http.response import JsonResponse
from web import models
from web.Forms.wiki import wiki_add_form
from django.urls import reverse
from django.views.decorators.csrf import csrf_exempt
from utils.tencent.cos import upload_img
from utils.encrypt import uid

'''
wiki
'''

def wiki(request, project_id):
    """wiki项目 首页"""
    # 详情内容展示
    wiki_id = request.GET.get('wiki_id')
    if not wiki_id or not wiki_id.isdecimal():
        return render(request, 'wiki.html')
    wiki_object = models.Wiki.objects.filter(id=wiki_id, project_id=project_id).first()
    return render(request, 'wiki.html', {'wiki_object': wiki_object})


def wiki_add(request, project_id):
    """文章添加"""
    if request.method == 'GET':
        form = wiki_add_form(request)
        return render(request, 'web/templates/wiki_form.html', locals())

    form = wiki_add_form(request, data=request.POST)
    if form.is_valid():
        # 判断用户是否已经选择父文章  form.instance.parent 前端选择的对象
        if form.instance.parent:
            # 当前字段的深度就等于父级的深度加一
            form.instance.depth = form.instance.parent.depth + 1
        else:
            form.instance.depth = 1
        form.instance.project = request.tracer.project
        form.save()
        url = reverse('wiki_add', kwargs={'project_id': project_id})
        return redirect(url)
    return render(request, 'wiki_form.html', locals())


def wiki_catalog(request, project_id):
    """多级目录显示"""
    # 获取数据
    data = models.Wiki.objects.filter(project=request.tracer.project).values('id', 'title', 'parent_id').order_by(
        'depth', 'id')
    return JsonResponse({'status': 1, 'data': list(data)})


def wiki_delete(request, project_id, wiki_id):
    """
    删除
    """
    models.Wiki.objects.filter(project_id=project_id, id=wiki_id).delete()
    return render(request, 'wiki.html')


def wiki_edit(request, project_id, wiki_id):
    """
     编辑
    """
    wiki_obj = models.Wiki.objects.filter(project_id=project_id, id=wiki_id).first()
    if not wiki_obj:
        url = reverse('wiki', kwargs={'project_id': project_id})
        return redirect(url)

    if request.method == 'GET':
        # instance=wiki_obj 自动帮你传参然后渲染出来
        form = wiki_add_form(request, instance=wiki_obj)
        return render(request, 'wiki_form.html', locals())

    # modelForm 自动帮你矫正
    form = wiki_add_form(request, data=request.POST, instance=wiki_obj)
    if form.is_valid():
        # 判断用户是否已经选择父文章  form.instance.parent 前端选择的对象
        if form.instance.parent:
            # 当前字段的深度就等于父级的深度加一
            form.instance.depth = form.instance.parent.depth + 1
        else:
            # 父级
            form.instance.depth = 1
        form.instance.project = request.tracer.project
        form.save()
        url = reverse('wiki', kwargs={'project_id': project_id})
        preview_url = '{}?wiki_id={}'.format(url, wiki_id)
        # print(preview_url)
        return redirect(preview_url)
    return render(request, 'wiki_form.html', locals())


@csrf_exempt
def wiki_upload(request, project_id):
    """图片上传"""
    # print(request.FILES.get('editormd-image-file'))
    result = {
        'success': 0,
        'message': None,
        'url': None
    }
    img_body_obj = request.FILES.get('editormd-image-file')
    if not img_body_obj:
        result['message'] = '图片不存在'
        return JsonResponse(result)

    # print(img_body_obj.name)
    Bucket = request.tracer.project.bucket
    region = request.tracer.project.region
    ext = img_body_obj.name.rsplit('.')[-1]
    key = '{}.{}'.format(uid(request.tracer.user.mobile_phone), ext)
    # 上传文件到cso
    img_url = upload_img(Bucket=Bucket, region=region, Body=img_body_obj, Key=key)
    result['success'] = 1
    result['url'] = img_url
    return JsonResponse(result)
